<template>
  <div style="padding: 30px">
    <!-- 搜索栏 -->
    <el-form
      :inline="true"
      :model="searchForm"
      class="demo-form-inline"
      v-show="showSearch"
    >
      <el-form-item label="职级选择">
        <el-select v-model="searchForm.grade" placeholder="请选择">
          <el-option
            v-for="item in gradeList"
            :key="item.id"
            :label="item.grade"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="queryForm">查询</el-button>
        <el-button @click="resetForm">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 表格上方按钮 -->
    <div>
      <div style="float: left; margin-bottom: 10px">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="addCategory"
          >新增大类</el-button
        >
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          @click="deleteSelect"
          >批量删除</el-button
        >
      </div>
      <div style="float: right">
        <el-tooltip class="item" effect="dark" content="隐藏搜索" placement="top">
          <el-button
            size="mini"
            circle
            icon="el-icon-search"
            @click="showSearchBar()"
          />
        </el-tooltip>
        <el-tooltip class="item" effect="dark" content="刷新" placement="top">
          <el-button
            size="mini"
            circle
            icon="el-icon-refresh"
            @click="queryCategory()"
          />
        </el-tooltip>
      </div>
    </div>
    <!-- 分类列表 -->
    <el-table
      :data="typeList"
      row-key="id"
      style="width: 100%"
      :header-cell-style="{ background: '#FAFAFA' }"
      border
      default-expand-all
      @selection-change="handleSelectionChange"
      :tree-props="{
        children: 'childrenList',
        hasChildren: 'childrenList.length>0',
      }"
    >
      
      <el-table-column type="selection" width="55" :selectable="checkSelect"> </el-table-column>
      <el-table-column prop="id" label="id" width="300"> </el-table-column>
      <el-table-column prop="courseName" label="名称"> </el-table-column>
      <!-- 层级：如果为1，显示“大类”，如果为2，显示“小类” -->
      <el-table-column prop="level" label="层级" width="150">
        <template slot-scope="scope">
          <span v-if="scope.row.level == 0">大类</span>
          <span v-if="scope.row.level == 1">小类</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="300" align="center">
        <template slot-scope="scope">
          <el-button
            type="text"
            size="medium"
            @click="edit(scope.row)"
            icon="el-icon-edit"
            v-if="scope.row.level < 2"
          >
            编辑
          </el-button>
          <el-button
            type="text"
            size="medium"
            @click="remove(scope.row)"
            icon="el-icon-delete"
            v-if="scope.row.level < 2"
          >
            删除
          </el-button>
          <el-button
            type="text"
            size="medium"
            v-if="scope.row.level < 1"
            @click="addSubCategory(scope.row)"
            icon="el-icon-circle-plus-outline"
          >
            新增小类（工种）
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 对话框 -->
    <el-dialog
      :title="dialogName"
      :visible.sync="dialogVisible"
      width="30%"
      :before-close="handleClose"
    >
      <el-form ref="form" :model="form" label-width="80px">
        <el-form-item label="类别名称">
          <el-input v-model="form.name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
import {
  getCategory,
  addRootCategory,
  addSubCategory,
  modifyCategory,
  removeCategory,
  getClassCategory,
} from "@/api/classification";
import {getGrade} from "@/api/edu/course";
import { mapGetters } from "vuex";
export default {
  computed: {
    ...mapGetters(["companyId"]),
  },

  data() {
    return {
      //所有分类
      typeList: [],
      //批量删除列表
      selectList: [],
      //对话框
      dialogName: "",
      //显示编辑
      dialogVisible: false,
      //编辑类别名
      form: {
        id: "",
        parentId: "",
        level: "",
        name: "",
      },
      //对话框类型
      dialogType: "",
      //是否显示搜索表单
      showSearch: true,
      //职级列表
      gradeList:[],
      //搜索表单
      searchForm: {
        grade: null,
      },
      // 职级
      grade : 100,
    };
  },

  created: function () {
    this.queryCategory();
    this.getGradeList();
  },
  methods: {
    //获取列表
    queryCategory() {
      getClassCategory(0, this.companyId, this.grade).then((res) => {
        const data = res.data;
        this.typeList = data.resList;
        // 对typeList进行多级遍历，在第三级遍历中将eduClassList赋值给childrenList
        this.typeList.forEach((item) => {
          if (item.childrenList) {
            item.childrenList.forEach((item2) => {
              if (item2.childrenList) {
                item2.childrenList = item2.eduClassList;
                item2.childrenList.forEach((item3) => {
                    item3.courseName = item3.className;
                });
              }
            });
          }
        });
        //console.log(this.typeList);
      });
    },
    //新增大类
    addCategory() {
      this.dialogType = "addRoot";
      this.dialogName = "新增大类";
      this.form.name = "";
      this.dialogVisible = true;
    },
    //删除单个
    remove: function (row) {
      var self = this;
      this.$confirm("此操作将删除该类别, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = []; //删除列表
          idArray.push(row.id);
          self.deleteAjax(idArray);
        })
        .catch(() => {});
    },
    //删除多个
    deleteSelect: function () {
      var self = this;
      if (this.selectList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("此操作将删除选择的所有类别, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          var idArray = [];
          self.selectList.forEach(function (type, index) {
            idArray.push(type.id);
          });
          self.deleteAjax(idArray);
        })
        .catch(() => {});
    },
    //删除Ajax请求
    deleteAjax: function (idArray) {
      var that = this;
      removeCategory(idArray).then((res) => {
        if (res.success) {
          this.$message({
            message: "删除成功",
            type: "success",
          });
          that.queryCategory();
        } else {
          this.$message({
            message: "删除失败,请先删除改类别对应的课程，试卷，课件",
            type: "warning",
          });
        }
      });
    },
    //添加子项类别
    addSubCategory(row) {
      this.dialogType = "addSub";
      this.dialogName = "新增小类（工种）";
      this.form.id = row.id;
      this.form.level = row.level;
      this.form.name = "";
      this.dialogVisible = true;
    },
    //编辑
    edit(row) {
      this.dialogType = "edit";
      this.dialogName = "编辑";
      this.form.id = row.id;
      this.form.level = row.level;
      this.form.name = row.courseName;
      this.dialogVisible = true;
    },
    //提交表单
    submitForm() {
      if (this.dialogType == "addRoot") {
        addRootCategory(this.form.name, this.companyId).then((res) => {
          this.queryCategory();
          this.dialogVisible = false;
        });
      } else if (this.dialogType == "addSub") {
        addSubCategory(this.form.id, this.form.name, this.form.level + 1).then(
          (res) => {
            this.queryCategory();
            this.dialogVisible = false;
          }
        );
      } else {
        modifyCategory(this.form.id, this.form.name).then((res) => {
          this.queryCategory();
          this.dialogVisible = false;
        });
      }
    },
    //批量删除列表
    handleSelectionChange: function (val) {
      this.selectList = val;
    },
    //关闭对话框
    handleClose(done) {
      this.$confirm("确认关闭？")
        .then((_) => {
          done();
        })
        .catch((_) => {});
    },
    // 判断是否可以选择
    checkSelect(row) {
      if (row.className) {
        return false;
      } else {
        return true;
      }
    },
    // 隐藏搜索栏
    showSearchBar() {
      this.showSearch = !this.showSearch;
    },
    // 查询
    queryForm() {
      this.grade = this.searchForm.grade;
      //console.log(this.grade);
      this.queryCategory();
    },
    // 重置
    resetForm() {
      this.searchForm.grade = "";
      this.grade = 100;
      this.queryCategory();
    },
    //获取职级列表
    getGradeList() {
      getGrade().then((res) => {
        if (res.success) {
          this.gradeList = res.data.resList;
        }
      });
    },
  },
};
</script>
<style scoped>
.edit-input {
  padding-right: 200px;
}
.cancel-btn {
  position: absolute;
  right: 15px;
  top: 10px;
}
</style>